package com.itstyle.quartz.config;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.itstyle.quartz.entity.QuartzEntity;
import com.itstyle.quartz.service.IJobService;

import java.util.List;

/**
 * 初始化一个测试Demo任务
 * 创建者 科帮网
 * 创建时间	2018年4月3日
 */
@Component
public class TaskRunner implements ApplicationRunner{
    
	private final static Logger LOGGER = LoggerFactory.getLogger(TaskRunner.class);
	
	@Autowired
    private IJobService jobService;
	@Autowired @Qualifier("Scheduler")
    private Scheduler scheduler;
	
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public void run(ApplicationArguments var) throws Exception{
		LOGGER.info("初始化测试任务");
		List<QuartzEntity> list = jobService.listQuartzEntityActivity();
    	if(list.size()>0){
			for(QuartzEntity quartz :list) {
				//构建job信息
				Class cls = Class.forName(quartz.getJobClassName()) ;
				cls.newInstance();
				JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
						quartz.getJobGroup())
						.withDescription(quartz.getDescription()).build();
				// 触发时间点
				CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
				Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger" + quartz.getJobName(), quartz.getJobGroup())
						.startNow().withSchedule(cronScheduleBuilder).build();
				//交由Scheduler安排触发
				JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
				scheduler.deleteJob(key);
				scheduler.scheduleJob(job, trigger);
			}
    	}
    }

}